package com.ai.service.made.impl;

import com.ai.check.CameraCheck;

import com.ai.common.CommonResponse;
import com.ai.entity.cameraFunctions.FullFunction;
import com.ai.entity.cameraFunctions.functions.CameraFunctionBindBO;
import com.ai.entity.cameraFunctions.functions.CameraFunctionsPO;
import com.ai.entity.cameraFunctions.functions.FunctionBasicsVO;
import com.ai.entity.cameraFunctions.timeInterval.TimeIntervalPO;
import com.ai.entity.cameraFunctions.timeInterval.TimeIntervalVO;
import com.ai.entity.function.FunctionPO;
import com.ai.entity.made.BaseIdOrNameBO;
import com.ai.entity.made.camera.CameraPO;
import com.ai.entity.made.camera.CameraVO;
import com.ai.entity.made.camera.SwitchCameraAlgorithmBO;
import com.ai.entity.made.camera.SwitchCameraFunctionAlgorithmBO;
import com.ai.mapper.made.CameraFunctionsMapper;
import com.ai.networking.netty.handler.ServerHandler;
import com.ai.service.made.*;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Mr.Chen
 * @since 2020-11-15
 */
@Slf4j
@Service
public class CameraFunctionsServiceImpl extends ServiceImpl<CameraFunctionsMapper, CameraFunctionsPO> implements CameraFunctionsService {
    @Resource
    RegionsService regionsService;

    @Resource
    TimeIntervalService timeIntervalService;

    @Resource
    CameraService cameraService;
    @Resource
    FunctionService functionService;
    @Resource
    private CameraFunctionsMapper cameraFunctionsMapper;
    @Resource
    private CameraFunctionsService cameraFunctionsService;
    @Override
    public void sendFullFunctions() {
        List<FullFunction> fullFunctionList = getFullFunctions();
        String KEY_ID = "ai";
        ServerHandler.sendMessage(KEY_ID, JSON.toJSONString(fullFunctionList));
    }

    @Override
    public List<FullFunction> getFullFunctions() {

        List<FullFunction> fullFunctionList = new ArrayList<>();

        List<FunctionPO> functionPOList = functionService.list();
        for (FunctionPO functionPO : functionPOList) {
            log.info("functionPO = " + JSON.toJSONString(functionPO));
            FullFunction fullFunction = new FullFunction();
            fullFunction.setType(functionPO.getType());
            fullFunction.setCameraList(getCameraByType(functionPO));
            fullFunctionList.add(fullFunction);
        }

        log.info("fullFunctionList = " + fullFunctionList);
        return fullFunctionList;
    }

    /**
     * 根据功能获取对应的所有摄像头信息，不包含摄像头的直播状态与功能状态
     *
     * @param functionPO
     * @return
     */
    @Override
    public List<SwitchCameraAlgorithmBO> getCameraByType(FunctionPO functionPO) {
        return getCameraByType(functionPO, null, null);
    }

    @Override
    public List<SwitchCameraAlgorithmBO> getCameraByType(FunctionPO functionPO, Integer status, Map<String, Object> extendedProperties) {

        int functionId = functionPO.getId();
        int type = functionPO.getType();

        List<SwitchCameraAlgorithmBO> switchCameraAlgorithmBOList = new ArrayList<>();

        List<CameraFunctionsPO> cameraFunctionsPOList = list(new QueryWrapper<CameraFunctionsPO>().eq("function_id", functionId));
        for (CameraFunctionsPO cameraFunctionsPO : cameraFunctionsPOList) {
            SwitchCameraAlgorithmBO switchCameraAlgorithmBO = new SwitchCameraAlgorithmBO();

            CameraPO cameraPO = cameraService.getById(cameraFunctionsPO.getCameraId());
            switchCameraAlgorithmBO.setCameraId(cameraPO.getId()).setCameraCode(cameraPO.getCode()).setUsername(cameraPO.getUsername()).setPassword(cameraPO.getPassword()).setIp(cameraPO.getIp()).setUrl(cameraPO.getUrl()).setPort(cameraPO.getPort()).setStreamWay(cameraPO.getStreamWay());

            if (status != null) switchCameraAlgorithmBO.setState(status); // 操作状态
            if (extendedProperties != null) switchCameraAlgorithmBO.setExtendedProperties(extendedProperties);// 附加属性

            List<SwitchCameraFunctionAlgorithmBO> functionList = new ArrayList<>();
            SwitchCameraFunctionAlgorithmBO functionAlgorithmBO = new SwitchCameraFunctionAlgorithmBO();
            functionAlgorithmBO.setId(cameraFunctionsPO.getId()).setType(type + "")
                    .setThreshold(cameraFunctionsPO.getThreshold())
                    .setSpecialOne(cameraFunctionsPO.getSpecialOne())
                    .setSpecialThree(cameraFunctionsPO.getSpecialTwo())
                    .setSpecialThree(cameraFunctionsPO.getSpecialThree())
                    .setSpecialFour(cameraFunctionsPO.getSpecialFour())
                    .setSpecialFive(cameraFunctionsPO.getSpecialFive())
                    .setTimeIntervals(timeIntervalService.getTimeIntervalList(cameraFunctionsPO.getId()))
                    .setSpots(regionsService.getSpots(cameraFunctionsPO.getId()));
            functionList.add(functionAlgorithmBO);

            switchCameraAlgorithmBO.setFunctions(functionList);
            switchCameraAlgorithmBOList.add(switchCameraAlgorithmBO);
        }
        return switchCameraAlgorithmBOList;
    }

    public CommonResponse cameraFunctionList(BaseIdOrNameBO baseIdOrNameBO) {
        CameraCheck cameraCheck = new CameraCheck();
        if (cameraCheck.isCheckID(baseIdOrNameBO.getCurrentId(), baseIdOrNameBO.getId())) {
            return cameraCheck.resultData;
        } else {
            int cameraId = baseIdOrNameBO.getId();
            String nickname = baseIdOrNameBO.getNickname();
            if (StringUtils.isEmpty(nickname)) {
                nickname = "%";
            } else {
                nickname = "%" + nickname + "%";
            }

            Map<String, List<FunctionBasicsVO>> map = new HashMap();
            List<FunctionBasicsVO> uncheckedList = this.cameraFunctionsMapper.unchecked(cameraId, nickname);
            List<FunctionBasicsVO> checkedList = this.cameraFunctionsMapper.checked(cameraId, nickname);
            map.put("unchecked", uncheckedList);
            map.put("checked", checkedList);
            return CommonResponse.ok(map);
        }
    }

    public CommonResponse checked(CameraFunctionBindBO cameraFunctionBindBO) {
        CameraCheck cameraCheck = new CameraCheck();
        if (cameraCheck.isCheckID(cameraFunctionBindBO.getCurrentId(), cameraFunctionBindBO.getCameraId())) {
            return cameraCheck.resultData;
        } else {
            int cameraId = cameraFunctionBindBO.getCameraId();
            List<Integer> functionIds = cameraFunctionBindBO.getFunctionIds();
            if (functionIds != null && functionIds.size() > 0) {
                List<CameraFunctionsPO> cameraFunctionsPOList = new ArrayList();
                Iterator var6 = functionIds.iterator();

                while (var6.hasNext()) {
                    int id = (Integer) var6.next();
                    CameraFunctionsPO cameraFunctionsPO = new CameraFunctionsPO();
                    cameraFunctionsPO.setFunctionId(id);
                    cameraFunctionsPO.setCameraId(cameraId);
                    cameraFunctionsPOList.add(cameraFunctionsPO);
                }
                // : 2023-06-07 通知算法，待完成
//                cameraFunctionsService.sendFullFunctions();

                return this.saveBatch(cameraFunctionsPOList) ? CommonResponse.ok("提交成功") :
                                                                CommonResponse.error("提交失败");
            } else {
                // : 2023-06-07 通知算法，待完成
//                cameraFunctionsService.sendFullFunctions();

                return CommonResponse.error("请选择需要绑定的功能");
            }
        }
    }

    public CommonResponse unchecked(CameraFunctionBindBO cameraFunctionBindBO) {
        CameraCheck cameraCheck = new CameraCheck();
        if (cameraCheck.isCheckID(cameraFunctionBindBO.getCurrentId(), cameraFunctionBindBO.getCameraId())) {
            // : 2023-06-07 通知算法，待完成
//            cameraFunctionsService.sendFullFunctions();

            return cameraCheck.resultData;
        } else {
            List<Integer> functionIds = cameraFunctionBindBO.getFunctionIds();
            if (functionIds != null && functionIds.size() > 0) {
//                cameraFunctionsService.sendFullFunctions();

                return this.removeByIds(functionIds) ? CommonResponse.ok("提交成功") : CommonResponse.error("提交失败");
            } else {
                // : 2023-06-07 通知算法，待完成
//                cameraFunctionsService.sendFullFunctions();

                return CommonResponse.error("请选择需要取消的功能");
            }
        }
    }

    public CommonResponse config(BaseIdOrNameBO baseIdOrNameBO) {
        if (baseIdOrNameBO.getId() == null) {
            return CommonResponse.error("请选择功能");
        } else {
            CameraFunctionsPO cameraFunctionsPO = (CameraFunctionsPO) this.getById(baseIdOrNameBO.getId());
            if (cameraFunctionsPO == null) {
                return CommonResponse.error("请选择功能");
            } else {
                TimeIntervalVO timeIntervalVO = new TimeIntervalVO();
                BeanUtils.copyProperties(cameraFunctionsPO, timeIntervalVO);
                List<TimeIntervalPO> timeList = this.timeIntervalService.list((Wrapper) (new QueryWrapper()).eq("camera_functions_id", baseIdOrNameBO.getId()));
                if (timeList.size() <= 0) {
                    TimeIntervalPO po = new TimeIntervalPO();
                    po.setId(0);
                    po.setCameraFunctionsId(baseIdOrNameBO.getId());
                    po.setStartTime("00:00:00");
                    po.setEndTime("23:59:59");
                    timeList.add(po);
                }

                timeIntervalVO.setTimeList(timeList);

                // : 2023-06-07 通知算法，待完成
//                cameraFunctionsService.sendFullFunctions();

                return CommonResponse.ok(timeIntervalVO);
            }
        }
    }

    public CommonResponse updateConfig(TimeIntervalVO timeIntervalVO) {
        Integer id = timeIntervalVO.getId();
        if (id != null && id != 0) {
            CameraFunctionsPO cameraFunctionsPO = new CameraFunctionsPO();
            BeanUtils.copyProperties(timeIntervalVO, cameraFunctionsPO);
            if (!this.updateById(cameraFunctionsPO)) {
                return CommonResponse.error("修改失败");
            } else {
                List<TimeIntervalPO> timeList = timeIntervalVO.getTimeList();
                if (timeList != null && timeList.size() > 0) {
                    this.timeIntervalService.remove((Wrapper) (new QueryWrapper()).eq("camera_functions_id", id));
                    timeList.forEach((timeIntervalPOx) -> {
                        timeIntervalPOx.setCameraFunctionsId(id);
                        this.timeIntervalService.save(timeIntervalPOx);
                    });
                } else {
                    TimeIntervalPO timeIntervalPO = new TimeIntervalPO();
                    timeIntervalPO.setCameraFunctionsId(timeIntervalVO.getId());
                    timeIntervalPO.setStartTime("00:00:00");
                    timeIntervalPO.setEndTime("23:59:59");
                    this.timeIntervalService.save(timeIntervalPO);
                }
                // : 2023-06-07 通知算法，待完成
//                cameraFunctionsService.sendFullFunctions();
                return CommonResponse.ok("修改成功");
            }
        } else {

            // : 2023-06-07 通知算法，待完成
//            cameraFunctionsService.sendFullFunctions();

            return CommonResponse.error("请选择功能");
        }
    }

    public CommonResponse listCameraByFunction(BaseIdOrNameBO baseIdOrNameBO) {
        if (baseIdOrNameBO.getId() == null) {
            return CommonResponse.error("请选择功能");
        } else {
            List<CameraVO> cameraVOList = this.cameraFunctionsMapper.listCameraByFunction(baseIdOrNameBO.getId());
            return CommonResponse.ok(cameraVOList);
        }
    }

    @Override
    public List<CameraPO> getCameraSteelList(ArrayList<Integer> funTypeList) {
        return    baseMapper.getCameraSteelList(funTypeList);
    }

    @Override
    public List<CameraFunctionsPO> getBindFunctions(int cameraId) {

        QueryWrapper<CameraFunctionsPO> queryWrapper = new QueryWrapper<CameraFunctionsPO>().eq("camera_id", cameraId);

        return this.list(queryWrapper);

    }
}
